import json
import uuid
import random

from django.core.cache import cache
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password, check_password
from django.urls import reverse

from book.models import Peoples, Book
from book.views_help import send_email_activate, send_email_fgemail, pc_icon


def menu(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        s_id = request.POST.get('s_id')
        s_pwd = request.POST.get('s_pwd')
        students = Peoples.objects.filter(s_id=s_id)
        if students.exists():
            students = students.first()
            print(students.s_id)
            if students.is_activate and not students.is_delete:
                username = students.username
                if check_password(s_pwd, students.s_pwd):
                    message = {
                        'message': f'{students.s_id}登陆成功',
                    }
                    print('ssss')
                    username = json.dumps(username)
                    if '202100' in s_id:
                        num = random.randint(100, 999)
                        response = redirect(reverse('book:user'))
                        data = username + s_id + str(num)
                        response.set_signed_cookie('data', data, 'yunpeng', max_age=60 * 60 * 24)
                        return response
                    else:
                        num = random.randint(100, 999)
                        response = redirect(reverse('book:user'))
                        data = username + s_id + str(num)
                        response.set_signed_cookie('data', data, 'yunpeng', max_age=60 * 60 * 24)
                        return response
                # else:
                #     print('aaaa')
                #     message = {
                #         'message': '账号或密码错误'
                #     }
                #     return render(request, 'login.html', context=message)
            else:

                data = {
                    'message': '用户未激活或已注销'
                }
                return render(request, 'login.html', context=data)
        else:
            message = {
                'message': '账号或密码错误'
            }
            return render(request, 'login.html', context=message)

    return HttpResponse('xxx')


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':

        sid = request.POST.get('s_id')

        if Peoples.objects.filter(s_id=sid):
            data = {
                'message': '此学号已被注册'
            }
            return render(request, 'register.html', context=data)

        elif len(sid) < 10 or len(sid) > 10:
            datas = {
                'message': '学号输入有误', }
            return render(request, 'register.html', context=datas)
        s_pwd = request.POST.get('s_pwd')
        g_id = request.POST.get('g_id')
        s_email = request.POST.get('s_email')
        username = request.POST.get('username')
        print(s_pwd)
        spwd = make_password(s_pwd)
        print(spwd)
        user = Peoples()
        user.s_id = sid
        user.s_pwd = spwd
        user.s_email = s_email
        user.username = username
        user.group_id = g_id
        user.save()
        u_token = uuid.uuid4().hex
        cache.set(u_token, sid, timeout=60 * 3)
        send_email_activate(s_email, sid, u_token)
        message = {
            'message': '请在三分钟内激活'
        }
        return render(request, 'login.html', context=message)
    else:
        return HttpResponse('不是正确请求')


def activate(request):
    u_token = request.GET.get('u_token')
    s_id = cache.get(u_token)
    if s_id:
        user = Peoples.objects.get(s_id=s_id)
        user.is_activate = True
        user.save()
        return HttpResponse('激活成功')
    else:
        return HttpResponse('学号不存在或激活过期，激活失败。请联系管理员进行激活')


def user(request):
    ordec = request.COOKIES.get('data')
    if ordec is None:
        return redirect(reverse('book:login'))
    else:
        data = request.get_signed_cookie('data', salt='yunpeng')
        s_id = data[-13:-3]
        name = data[:-13]
        print(s_id)
        name = json.loads(name)
        print(name)
        message = {
            'message': f'{name}欢迎进入云云图书管理',
        }
    return render(request, 'user.html', context=message)


def logout(request):
    response = redirect(reverse('book:login'))
    response.delete_cookie('data')
    return response


def fg_pwd(request):
    if request.method == 'GET':
        return render(request, 'fg_pwd.html')
    elif request.method == 'POST':
        s_id = request.POST.get('s_id')
        s_email = request.POST.get('s_email')
        user = Peoples.objects.get(s_id=s_id)
        if user.s_email == s_email:
            u_token = uuid.uuid4().hex
            cache.set(u_token, s_id, timeout=60 * 3)
            print(u_token)
            send_email_fgemail(s_email, s_id, u_token)

            return HttpResponse('发送成功')
        else:

            return HttpResponse('学号与绑定邮箱错误')


def get_pwd(request):
    if request.method == 'GET':
        try:
            u_token = request.GET.get('u_token')
            s_id = cache.get(u_token)
            data = {
                's_id': s_id
            }
            return render(request, 'get_pwd.html', context=data)
        except Exception as e:
            print(e)
    else:
        s_id = request.POST.get('s_id')
        s_pwd = request.POST.get('s_pwd')
        ss_pwd = request.POST.get('ss_pwd')
        if ss_pwd == s_pwd:
            if s_id:
                user = Peoples.objects.get(s_id=s_id)
                s_pwd = request.POST.get('s_pwd')
                s_pwd = make_password(s_pwd)
                user.s_pwd = s_pwd
                user.save()
                s_id = None
                message = {
                    'message': '修改成功'
                }
                return render(request, 'login.html', context=message)
            else:
                return HttpResponse('超时修改，或学号错误')
        else:
            return HttpResponse('密码不一致，请重新输入。')


def add_book(request):
    if request.method == 'GET':
        return render(request, 'add_book.html')
    elif request.method == 'POST':
        b_name = request.POST.get('b_name')
        b_url = 'https://book.douban.com/j/subject_suggest'
        b_img = pc_icon(b_url, b_name)

        if b_img == 1:
            return HttpResponse('上传出错')
        b_writer = request.POST.get('b_writer')
        b_position = request.POST.get('b_position')
        b_num = request.POST.get('b_num')
        b_note = request.POST.get('b_note')
        b_snum = b_num
        book = Book()
        book.b_name = b_name
        book.b_img = b_img
        book.b_num = b_num
        book.b_note = b_note
        book.b_writer = b_writer
        book.b_position = b_position
        book.b_snum = b_snum
        book.save()
    return HttpResponse('成功')


def root(request):
    return render(request, 'root.html')
def book_check(request):
    books = Book.objects.all()

    b_list = []
    datas={
        'code':200,
        'message':'success',
        'data':b_list
    }
    for book in books:
        data ={

        }
        b_name = book.b_name
        b_writer = book.b_writer

        data={
            'b_name':b_name,
            'n_writer':b_writer
        }
        b_list.append(data)
    return JsonResponse(data=datas)
